<template>
  <div class="left-tree" style="overflow:auto">
    <div class="tree-title">
      <el-input v-model="filterText" :size="size" type="text" style="width:95%" prefix-icon="el-icon-search"
                :placeholder="placeholder"
                clearable="clearable"></el-input>
    </div>
    <el-scrollbar>
      <el-tree class="tree-body"
               :data="reqTree"
               style="height:860px;"
               :props="props"
               node-key="id"
               default-expand-all
               @node-click="goRouter"
               :filter-node-method="filterNode"
               highlight-current
               :expand-on-click-node="false"
               ref="tree"
      >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                        <i class="fa fa-folder-open-o" aria-hidden="true" v-if="!data.isLeaf"></i>
                        <i class="fa fa-info" aria-hidden="true" v-if="data.isLeaf"></i>
              <span v-if="!data.isChangeName">{{ node.label }}</span>
              <el-input v-else type="text" size="mini" v-model="data.label" style="width: 120px"
                        @keydown.enter.native="renameAfter(data)"></el-input>
              <span class="left-tree-btns">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
                  </span>
              <el-dropdown-menu size="small" slot="dropdown">
                <el-dropdown-item>
                  <i class="fa fa-edit" aria-hidden="true"></i>
                  <el-button type="text" size="mini" @click="() => rename(data)">重命名</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!data.isLeaf">
                  <i class="fa fa-plus-square" aria-hidden="true"></i>
                  <el-button type="text" size="mini" @click="() => newReqFav(data)">新增收藏夹</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!data.isLeaf">
                  <i class="icon iconfont icon-xinzeng"></i>
                  <el-button type="text" size="mini" @click="() => newReq(data)">新增请求</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                   <i class="icon iconfont icon-shanchu"></i>
                   <el-button type="text" size="mini" @click="() => remove(data)">删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
        </span>
      </span>
      </el-tree>
    </el-scrollbar>
    <el-dialog title="新增请求" :visible.sync="editform.dialogFormVisible" width="40%" center>
      <el-form :model="editform" label-width="40%" size="small">
        <el-row :gutter="24" align="center">
          <el-col :span="4">
            <el-form-item label="">
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求名称：">
              <el-input v-model="treeForm.label"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editform.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickButton()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { mapState, mapActions, mapMutations } from 'vuex';
  import axios from '../../axios';
  import Api from '../../constants/Api';
  import { SUCCESS_CODE } from '../../constants/constant';

  export default {
    name: 'reqTree',
    props: {
      data: {
        required: true,
        type: Object
      }, // 表单域（必传）
      placeholder: {
        type: String,
        default: '按条件筛选'
      }, // 占位文本
      size: {
        type: String,
        default: 'small'
      }, // 大小，可取值medium / small / mini
      clearable: {
        type: Boolean,
        default: true
      }, // 是否可以清空选项
      // 配置项
      props: {
        type: Object,
        default: () => {
          return {
            // ID字段名
            value: 'id',
            // 显示名称
            label: 'label',
            // 是否重命名
            isChangeName: false,
            // 是否是请求
            isLeaf: 'isLeaf',
            // 子级字段名
            children: 'children'
          };
        }
      }
    },
    data() {
      return {
        filterText: '',
        editform: {
          dialogFormVisible: false,
          // 服务器IP
          svrIp: '',
          // 服务器IP
          svrPort: '',
          // 上一级ID
          parentId: '',
          // 自己的ID
          favId: '',
          // 模板ID
          tmplId: 'req',
        },
        treeForm: {
          id: 1000,
          label: '新建请求',
          favLabel: '新建收藏夹',
          isLeaf: false,
        },
        defualId: 1,
        id: 1000,
      };
    },
// 获取树并默认展开
    created() {
      const vm = this;
      vm.getReqTree(vm);
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    computed: {
      ...mapState({
        reqTree: state => state.app.reqTree,
        methodList: state => state.staticParamList.methodList,
        tagsList: state => state.app.tagsList
      }),
    },
    methods: {
      ...mapMutations(['delTags']),
      ...mapActions(['getReqTree']),
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      rename(data) {
        data.isChangeName = true;
      },
      // 默认前端新建请求收藏夹方法[假新建，不与后端交互] start
      append(data) {
        const vm = this;
        let id = vm.id;
        const newChild = {
          id: id++,
          label: '新建收藏夹',
          isChangeName: false,
          children: []
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },
      // 默认前端新建请求收藏夹方法[假新建，不与后端交互] end
      // 默认前端新建请求方法[假新建，不与后端交互] start
      appendReq(data) {
        const vm = this;
        let id = vm.id;
        const newChild = {
          id: id++,
          label: '新建请求',
          isChangeName: false,
          isLeaf: true,
          children: []
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },
      // 默认前端新建请求方法[假新建，不与后端交互] end
      remove_old(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },
      // 重命名回车绑定事件 start
      renameAfter(data) {
        const vm = this;
        if (data.isLeaf) {
          vm.updateReq(data);
        } else {
          vm.updateReqFav(data);
        }
      },
      // 重命名回车绑定事件end
      // 收藏夹重命名方法 start
      updateReqFav(data) {
        const vm = this;
        vm.treeForm.favLabel = data.label;
        axios.post(Api.updateReqFav, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            favName: vm.treeForm.favLabel,
            favId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              data.isChangeName = false;
              vm.getReqTree(vm);
              vm.$message.success('收藏夹重命名成功');
              vm.treeForm.favLabel = '新建收藏夹';
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 收藏夹重命名方法 end
      // 请求重命名方法 start
      updateReq(data) {
        const vm = this;
        vm.treeForm.label = data.label;
        axios.post(Api.updateReq, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            reqName: vm.treeForm.label,
            reqId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              data.isChangeName = false;
              vm.getReqTree(vm);
              vm.$message.success('请求重命名成功');
              vm.treeForm.label = '新建请求';
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 请求重命名方法 end
      // 前端新建请求方法 start
      newReq(data) {
        const vm = this;
        vm.editform.dialogFormVisible = true;
      },
      // 前端新建请求方法 end
      // 前端新建收藏夹方法 start
      newReqFav(data) {
        const vm = this;
        axios.post(Api.newReqFav, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            favName: vm.treeForm.favLabel,
            parentId: vm.editform.parentId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getReqTree(vm);
              vm.$message.success('新增文件夹成功');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端新建收藏夹方法 end
      // 删除绑定事件 start
      remove(data) {
        const vm = this;
        if (data.isLeaf) {
          vm.removeReq(data);
        } else {
          vm.removeReqFav(data);
        }
      },
      // 删除绑定事件end
      // 前端删除请求方法 start
      removeReq(data) {
        const vm = this;
        axios.post(Api.removeReq, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            reqId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getReqTree(vm);
              vm.deleteTag();
              vm.$message.success('删除请求成功');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端删除请求方法 end
      // 前端删除请求方法 start
      removeReqFav(data) {
        const vm = this;
        axios.post(Api.removeReqFav, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            favId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getReqTree(vm);
              vm.$message.success('删除收藏夹成功');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端删除请求方法 end
      // 前端新建请求页面确定按钮绑定事件 start
      clickButton() {
        const vm = this;
        vm.editform.dialogFormVisible = true;
        axios.post(Api.newReq, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            reqName: vm.treeForm.label,
            favId: vm.editform.parentId,
            tmplId: vm.editform.tmplId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getReqTree(vm);
              vm.$router.push({
                name: 'req',
                params: {
                  id: res.data.reqId,
                  label: res.data.reqName,
                }
              });
              vm.$message.success('新增成功');
            } else {
              this.$message.error(res.message);
            }
            vm.editform.dialogFormVisible = false;
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端新建请求页面确定按钮绑定事件 end
      // 新增页面跳转
      goRouter: function (node) {
        const vm = this;
        vm.editform.favId = node[this.props.value];
        console.log('默认点击事件为请求' + node[this.props.value]);
        if (node[this.props.isLeaf]) {
          vm.$router.push({
            name: 'req',
            params: {
              id: node[this.props.value],
              label: node[this.props.label],
            }
          });
        } else {
          vm.editform.parentId = node[this.props.value];
          console.log('默认点击事件为文件夹' + node[this.props.value]);
        }
      },
      // 关闭删除树的tag页
      deleteTag() {
        let curIndex = 0;
        let path = '/req/' + this.editform.favId;
        this.tagsList.forEach((item, index) => {
          if (item.path === path) {
            curIndex = index;
            this.closeTags(curIndex);
          }
        });
      },
      // 关闭单个标签
      closeTags(index) {
        this.delTags({
          index,
          callback: res => {
            const delItem = res.delItem;
            const item = res.item;
            if (item) {
              delItem.path === this.$route.fullPath && this.$router.push(item.path);
            } else {
              this.$router.push('/');
            }
          }
        });
      },
    }
  };
</script>

<style lang='scss' scoped>
  .left-tree {
    border: 1px solid #ebeef5;
    border-radius: 3px;

    .tree-title {
      padding: 10px;
      font-size: 16px;
      font-weight: 600;
      text-align: left;
      border-bottom: 1px solid #ebeef5;
    }

    .fa {
      margin-right: 10px;
    }

    .left-tree-btns {
      margin-left: auto;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 14px;
      padding-right: 8px;

      .el-dropdown-link {
        height: 40px;
        cursor: pointer;
        padding: 12px 15px;
        margin-top: 12px;
      }
    }

    .el-tree-node__content {
      width: auto;
      margin-top: 12px;
      float: right;
      font-family: “Trebuchet MS”, Arial, Helvetica, sans-serif;
      font-size: 14px;
      color: #2a2e33;
      line-height: 25px;
      letter-spacing: 1px;
    }

    .tree-body {
      padding: 1px;
      overflow: auto;
      margin: 1px;
      /*height: 700px;*/
      overflow-y: auto;
      font-size: 22px;
      color: #2a2e33;

      > > > .el-tree-node {
        > .el-tree-node__children {
          height: 30px;
          overflow: visible !important
        }
      }
    }
  }
</style>
<style lang='scss'>
  .left-tree {
    .el-input--mini .el-input__inner {
      height: 20px;
      line-height: 20px;
    }
  }
</style>
